package com.student.util;

import java.sql.*;
import java.util.Properties;

public class DBUtil {

    private static String url;
    private static String user;
    private static String password;

    static {

        try{
            Properties config=new Properties();
            config.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
            url= config.getProperty("jdbc.url");
            user= config.getProperty("jdbc.user");
            password= config.getProperty("jdbc.password");
            Class.forName(config.getProperty("jdbc.driver","com.mysql.jdbc.Driver"));
        }catch (Exception ex){
            ex.printStackTrace();
            System.exit(0);
        }
    }

    private DBUtil(){}


    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }


    public static void setParam(PreparedStatement pstmt,Object... objs) throws Exception{
        if (objs==null||objs.length==0){
            return;
        }
        for (int i = 0; i < objs.length; i++) {
            pstmt.setObject(i+1,objs[i]);
        }
    }

    public static int execute(String sql,Object...objs) throws Exception {
        try(
                Connection conn=getConnection();
                PreparedStatement pstmt=conn.prepareStatement(sql);
        ){
            setParam(pstmt,objs);
            return pstmt.executeUpdate();
        }
    }

    public static void close(Connection conn, Statement stmt){
        try{
            stmt.close();
        }catch (Exception e){
        }
        try{
            conn.close();
        }catch (Exception e){
        }
    }
    public static void close(Connection conn, Statement stmt, ResultSet re){
        try{
            re.close();
        }catch (Exception e){
        }
        close(conn,stmt);
    }

    public static void main(String[] args)throws Exception {
        System.out.println(getConnection());
    }
}
